﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Media;
using System.Threading;

using Utilities.IO;
using Utilities.Media.Audio;
using Utilities.Media.Containers;
using Utilities.Media.Containers.Wav;
using Utilities.Windows.Interop;

namespace Utilities.Windows.Media
{
    public class AudioPlayer
    {
        public AudioStream Stream { get; protected set; }
        public TimeSpan BufferDuration { get; set; }

        private Queue<AudioBuffer> bufferQueue;
        private QueueStream queueStream;

        private WaveOut waveOut;

        public AudioPlayer()
        {
            BufferDuration = new TimeSpan(0, 0, 1);

            bufferQueue = new Queue<AudioBuffer>();
            queueStream = new QueueStream();
        }

        public void Play(AudioStream stream)
        {
            Stream = stream;
            waveOut = new WaveOut(Stream.NumChannels, Stream.SampleRate, stream.BitsPerSample);

            new Thread(BufferThread).Start();
        }

        private void BufferThread()
        {
            while (true)
            {
                while (bufferQueue.Sum(b => b.Duration) < BufferDuration)
                {
                    AudioBuffer buffer = Stream.ReadBuffer();
                    bufferQueue.Enqueue(buffer);

                    //waveOut.Write();

                    queueStream.Write(buffer.Data, 0, buffer.Data.Length);
                }
                Thread.Sleep(100);
            }
        }
    }
}
